package cn.zhangchg.leetcode.arrays;

import java.util.Arrays;

/**
 *
 */
public class MergeSortArray3 {
    public static void main(String[] args) {
        MergeSortArray3 mergeSortArray = new MergeSortArray3();
        Integer[] ints = {0, 2, 3, 4};
        System.err.println(Arrays.toString(ints));
        Integer[] merge = mergeSortArray.merge(ints, new Integer[]{1, 3, 4, 5});
        System.err.println(Arrays.toString(ints));
        System.err.println(Arrays.toString(merge));
    }

    public <T extends Comparable<T>> T[] merge(T[] nums1, T[] nums2) {
        if (nums1.length <= 0) {
            return nums2;
        }
        if (nums2.length <= 0) {
            return nums1;
        }


        // 若你需要的是泛型方法，可以这样做
        Class<T> clazz = (Class<T>) nums1.getClass().getComponentType();
        T[] result = Arrays.copyOf(nums1, nums1.length + nums2.length);
        //System.arraycopy(nums2, 0, result, nums1.length, nums2.length);

        int i = 0, j = 0, k = 0;
        while (i <= nums1.length - 1 && j <= nums2.length - 1) {
            if (nums1[i].compareTo(nums2[j]) > 0) {
                result[k++] = nums2[j++];
            } else {
                result[k++] = nums1[i++];
            }
        }
        if (i == nums1.length) {
            while (j < nums2.length) {
                result[k++] = nums2[j++];
            }
        }

        if (j == nums1.length) {
            while (i < nums2.length) {
                result[k++] = nums2[i++];
            }
        }
        return result;
    }
}
